(function($){
    var _onchange = function(event){
        var $ref = $("#"+event.data.ref);
        if ($ref.size() == 0) return false;
        if(event.data.$this.val() == null) return false;
        Bolt.ajax('doajax',{
            data:{},
            cache: false,
            url:event.data.refUrl.replace("{value}",encodeURIComponent(event.data.$this.val())),
            okCallback:function(content){
                _comboxRefresh($ref, content['data']);
            }
        })
    };

    var _comboxRefresh = function($select, json){
        if (!json) return;
        var html = '', selected = '';
        var nextVal = $select.data('value');
        $.each(json, function(i){
            if (json[i] && json[i].length > 1){
                if (typeof nextVal !== 'undefined') selected = json[i][0] == nextVal ? ' selected' : ''
                html += '<option value="'+json[i][0]+'"'+ selected +'>' + json[i][1] + '</option>';
            }
        });

        $select.empty();
        $select.html(html);
        $select.trigger("change");
    };

    var _comboxReset = function($select){
        var $box = $select.parents('div.select:first'),
            defaultValue = $box.find('>a').attr('default-value');
        $('#op_'+$box.attr('id')).find('>li a[value="'+defaultValue+'"]').trigger('click');
    };

    var Plugin = function(){
        return this.each(function() {
            var $element = $(this);
            var ref = $element.attr("ref");
            var refUrl = $element.attr("refUrl") || "";
            if (ref && refUrl) {
                refUrl = refUrl.trim();
                $element.unbind("change", _onchange).bind("change", {ref:ref, refUrl:refUrl, $this:$element}, _onchange);
            }
            $element.trigger("change");
        })
    }

    $.fn.ldSelect = Plugin

    Bolt.addComponent({
        name: "ldSelect",
        plugin: Plugin,
        runPoint: Bolt.eventType.afterAjaxPageShow,
        expr: "select[data-toggle='ldSelect']",
        order: 800
    })

})(jQuery);